package com.yune.activity.login;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.yune.activity.App;
import com.yune.activity.main.MainActivity;
import com.yune.activity.sign.SignActivity;
import com.yune.databinding.ActivityLoginBinding;
import com.yune.utils.Network;

import org.json.JSONException;
import org.json.JSONObject;
public class LoginViewModel extends AndroidViewModel {
    public static MutableLiveData<String> account=new MutableLiveData<>();//MutableLiveData可变LiveData
    public static MutableLiveData<String> password=new MutableLiveData<>();
    public static MutableLiveData<Boolean> autoLogin=new MutableLiveData<>();//autoLogin自动登录
    @SuppressLint("StaticFieldLeak")
    private LoginActivity loginActivity;
    public LoginViewModel(@NonNull Application application) {
        super(application);
    }
    public void setBinding(ActivityLoginBinding binding, LoginActivity loginActivity) {
        account.setValue("");
        password.setValue("");
        autoLogin.setValue(false);
        this.loginActivity=loginActivity;
        autoLogin();
    }
    //自动登录
    private void autoLogin() {
        if (App.sp.getBoolean("autoLogin",false)){
            Network.get("https://api2.bmob.cn/1/login?username="+App.sp.getString("account","")+"&password="+App.sp.getString("password",""), res -> {
                if (res!=null){
                    try {
                        JSONObject jsonObject = new JSONObject(res);
                        if (jsonObject.isNull("error")){
                            SharedPreferences.Editor edit = App.sp.edit();
                            edit.putString("loginMsg",jsonObject.toString());
                            edit.apply();//应用、申请
                            loginActivity.startActivity(new Intent(loginActivity, MainActivity.class));//从loginActivity登录页跳到主页及MainActivity发现页
                            loginActivity.finish();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        Toast.makeText(loginActivity, "登录失败", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }
    public void findPassword(View view){
        EditText editText=new EditText(loginActivity);
        editText.setHint("请输入邮箱");
        AlertDialog.Builder dialog=new AlertDialog.Builder(loginActivity);
        dialog.setTitle("发邮件找回密码").setView(editText).setPositiveButton("确定", (dialog1, which) -> {
            JSONObject jo=new JSONObject();
            try {
                jo.put("email",editText.getText().toString().trim());//trim修剪
                Network.post(jo, "https://api2.bmob.cn/1/requestPasswordReset", res ->{//requestPasswordReset请求密码重置
                    loginActivity.runOnUiThread(() -> Toast.makeText(loginActivity,"已发送改密邮件",Toast.LENGTH_SHORT).show());
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).setNegativeButton("取消",null).show();
    }
    public void login(View view){
        if (account.getValue().equals("")){//equals等于
            Toast.makeText(loginActivity, "请输入账号", Toast.LENGTH_SHORT).show();return;
        }
        if (password.getValue().equals("")){
            Toast.makeText(loginActivity, "请输入密码", Toast.LENGTH_SHORT).show();return;
        }
        Network.get("https://api2.bmob.cn/1/login?username="+account.getValue()+"&password="+password.getValue(), res -> {
            if (res!=null){
                try {
                    JSONObject jsonObject = new JSONObject(res);
                    if (!jsonObject.isNull("error")){
                        loginActivity.runOnUiThread(() -> Toast.makeText(loginActivity, "登录失败", Toast.LENGTH_SHORT).show());
                    }else { //保存账号和密码到，下载自动登录
                        SharedPreferences.Editor edit = App.sp.edit();
                        edit.putBoolean("autoLogin",autoLogin.getValue());
                        edit.putString("loginMsg",jsonObject.toString());
                        edit.putString("account",account.getValue());
                        edit.putString("password",password.getValue());
                        edit.apply();//apply申请、 应用
                        loginActivity.startActivity(new Intent(loginActivity, MainActivity.class));
                        loginActivity.finish();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    Toast.makeText(loginActivity, "登录失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    public void toSign(View view){ loginActivity.startActivity(new Intent(loginActivity, SignActivity.class)); }
}//从登录页跳到注册页接口